using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace CodePlex.SpaceBlock.UI
{
    public static class TransientSettings
    {

        private static XmlDocument __doc;


        private static XmlDocument Doc
        {
            get
            {
                if (__doc == null)
                {
                    __doc = new XmlDocument();
                    try
                    {
                        __doc.LoadXml(Properties.Settings.Default.TransientSettings);
                    }
                    catch { }
                }
                return __doc;
            }
        }

        public static XmlElement GetSettings(string name)
        {
            XmlElement settingElement = Doc.SelectSingleNode(string.Format(@"Setting[@Name=""{0}""]", name)) as XmlElement;
            if (settingElement == null)
            {
                return Doc.CreateElement("Empty");
            }

            return settingElement.FirstChild.CloneNode(true) as XmlElement;
        }

        public static void SaveSettings(string name, XmlElement settings)
        {
            settings = settings ?? Doc.CreateElement("Empty");
            XmlElement imported = Doc.ImportNode(settings,true) as XmlElement;

            XmlElement settingElement = Doc.SelectSingleNode(string.Format(@"Setting[@Name=""{0}""]", name)) as XmlElement;

            if (settingElement == null)
            {
                XmlElement settingsElement = Doc.CreateElement("Setting");
                settingsElement.SetAttribute("Name", name);
                settingsElement.AppendChild(imported);
                Doc.AppendChild(settingsElement);
            }
            else
            {
                settingElement.ReplaceChild(imported, settingElement.FirstChild);
            }

            
            // save to .net app settings
            StringWriter sw = new StringWriter();
            Doc.Save(sw);
            Properties.Settings.Default.TransientSettings = sw.ToString();
            Properties.Settings.Default.Save();

        }




    }
}
